<template>
  <div class="app-container">
    <el-dialog title="人员选择"
               :visible="peopleDialogVisible"
               width="70%"   :before-close="handleClose">
      <div class="el-dialog-div">
         <el-row :gutter="20">
            <!--部门数据-->
            <el-col :span="4" :xs="24">
              <div class="head-container">
                <el-input
                  v-model="deptName"
                  placeholder="请输入部门名称"
                  clearable
                  size="small"
                  prefix-icon="el-icon-search"
                  style="margin-bottom: 20px"
                />
              </div>
              <div class="head-container">
                <el-tree
                  :data="deptOptions"
                  lazy
                  :load="queryDept"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="tree"
                  node-key="id"
                  highlight-current
                  @node-click="handleNodeClick"
                />
              </div>
            </el-col>
            <!--用户数据-->
            <el-col :span="15" :xs="24">
              <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
                <el-form-item label="用户名称" prop="userName">
                  <el-input
                    v-model="queryParams.nickName"
                    placeholder="请输入用户名称"
                    clearable
                    style="width: 240px"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" size="mini" @click="searchPeople">搜索</el-button>
                </el-form-item>
              </el-form>
              <el-table ref="multipleTable" v-loading="loading" :data="userList" @select="handleSelectionChange" :height="300">
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column label="所属部门" align="center" key="deptPath" prop="dept.deptPath" v-if="columns[7].visible" :show-overflow-tooltip="true" />
                <el-table-column label="用户账号" align="center" key="userName" prop="userName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
                <el-table-column label="用户姓名" align="center" key="nickName" prop="nickName" v-if="columns[2].visible" :show-overflow-tooltip="true" />
                <el-table-column label="状态" align="center" key="status" v-if="columns[5].visible">
                  <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.status"
                      active-value="0"
                      inactive-value="1"
                      disabled
                      active-color="#13ce66"
                      inactive-color="#ff4949"
                    ></el-switch>
                  </template>
                </el-table-column>
                <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="columns[0].visible" />
              </el-table>

              <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
              />
            </el-col>
            <!--已选用户-->
            <el-col :span="5" :xs="24">
             <el-card class="box-card">
                已选用户
                <el-divider></el-divider>
                <el-tag
                 :key="tag.loginName"
                 v-for="tag in ids"
                 closable
                 :disable-transitions="false"
                 @close="delSelected(tag)">
               {{tag.userName}}
             </el-tag>
             </el-card>
           </el-col>
          </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button  @click="cancel">取 消</el-button>
        <el-button type="primary" @click="sureOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
import {changeUserStatus, deptTreeSelect, listUser} from "@/api/system/user";

export default {
  name: "PeopleSelect",
  props:{
    peopleDialogVisible: {
      type: Boolean,
      default: false,
    },
    //界面有多个地方需要选部门的时候传过来做区别
    funType:{
      type: String
    }
  },
  data() {
    return {
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        nickName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true },
        { key: 7, label: `部门路径`, visible: true }
      ],
    }
  },
  created() {
    this.queryParams.deptId = 0;
    this.getList();
    this.getDeptTree();
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      deptTreeSelect({"deptName":val}).then(response => {
        this.deptOptions = response.data;
      });
    },
  },
  methods:{
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      let that = this;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
          setTimeout(function (){
            that.flreshChecked();
          },500)
        }
      );
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect({"parentId":0}).then(response => {
        this.deptOptions = response.data;
      });
    },
    queryDept(node, resolve){
      let data = node.data;
      let params = {};
      if(Array.isArray(data)){
        resolve(data);
        return ;
      }
      if(data !=undefined){
        params = {"parentId":data.id};
        deptTreeSelect(params).then(response => {
          resolve(response.data);
        });
      }else{
        resolve([]);
      }
    },
    searchPeople(){
      this.queryParams.deptId=null;
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    uniqueUser(arr) {
      return arr.filter((item, index) => {
        return arr.findIndex(obj => obj.loginName === item.loginName) === index;
      });
    },
    flreshChecked(){
      //根据当前已选数据自动勾选当前数据页
      //右边删除已选数据时，刷新选项，
      let selected = this.userList.filter(item=>{
        let flag=0;
        this.ids.forEach((one,i)=>{
          if(item.userName===one.loginName){
            flag++;
          }
        });
        return flag>0?true:false;
      });
      try{
        this.$refs.multipleTable.clearSelection();
      }catch(e){}
      selected.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(row,true);
      });
    },
    filterNoselect(checkeds){
      //解决表格check的时候，右边已选用户没有变
      //先去已选数据中除所有当前页面数据，然后加上选上的数据
      this.ids = this.ids.filter(item =>{
        let flag=0;
        this.userList.forEach((row,i)=>{
          if(item.loginName===row.userName){
            flag++;
          }
        });
        return flag>0?false:true;
      });
      let data = checkeds.map(item => {
        return {"loginName":item.userName,"userName":item.nickName};
      });
      if(data.length>0){
        this.ids = this.ids.concat(data);
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection,row) {
      let data = selection.map(item => {
        return {"loginName":item.userName,"userName":item.nickName};
      });
      if(data.length>0){
        this.ids = this.ids.concat(data);
      }
      this.ids = this.uniqueUser(this.ids);
      this.filterNoselect(selection);
      // this.single = selection.length != 1;
      // this.multiple = !selection.length;
    },
    handleClose(done) {
      this.$emit("update:peopleDialogVisible", false);
      done();
      this.ids = [];
    },
    handleNodeClick(data){
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function() {
        return changeUserStatus(row.userId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    cancel(){
      this.ids = [];
      this.$refs.multipleTable.clearSelection();
      this.$emit("update:peopleDialogVisible", false);
    },
    sureOk(){
      alert(JSON.stringify(this.ids));
    },
    delSelected(tag){
      this.ids = this.ids.filter(item => item.loginName !== tag.loginName);
      this.flreshChecked();
    },
  }
}
</script>

<style scoped>
.el-dialog-div {
  height: 60vh;
  overflow-x: hidden;
}
.box-card {
  width: 120px;
  height: 380px;
}
</style>
